﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace GiteeFirstProject.EntityFramwork.Models
{
    public class StudentRepository : IStudentRepository
    {
        private readonly AppDbContext _context;

        public StudentRepository(AppDbContext context)
        {
            _context = context;
        }

        public void Create(Student entity)
        {
            entity.Id = Guid.NewGuid();
            _context.Add(entity);
            _context.SaveChanges();
        }

        public void Delete(Student entity)
        {
            var model = _context.Find<Student>(entity.Id);
            if(model == null)
            {
                throw new Exception("删除的对象不存在，请重试"); 
            }

            _context.Remove(model);
            _context.SaveChanges();
        }

        public Student Query(Expression<Func<Student, bool>> filter)
        {
            return _context.Students.FirstOrDefault(filter);
        }

        public IQueryable<Student> QueryList(Expression<Func<Student, bool>> filter)
        {
            return _context.Students.Where(filter);
        }

        public void Update(Student entity)
        {
            var model = _context.Find<Student>(entity.Id);
            if (model == null)
            {
                throw new Exception("修改的对象不存在，请重试");
            }

            model.StuAge = entity.StuAge;
            model.StuNum = entity.StuNum;
            model.StuName = entity.StuName;
            _context.Update(model);
            _context.SaveChanges();
        }
    }
}
